package com.atguigu.edu.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.bean.BaseDbTableProcess;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

public class BaseDbTableProcessFunction extends BroadcastProcessFunction<JSONObject,String,JSONObject> {
    MapStateDescriptor<String, BaseDbTableProcess> mapStateDescriptor;
    private Map<String, BaseDbTableProcess> configMap = new HashMap<>();


    @Override
    public void open(Configuration parameters) throws Exception {
        //将配置表中的配置信息预加载到程序中
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/edu_config?" +
                "user=root&password=000000&useUnicode=true&" +
                "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");

        //获取数据库操作对象
        String sql = "select * from edu_config.table_process_dwd";
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行SQL语句
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        //处理结果集
        while (rs.next()) {
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName, columnValue);
            }
            //将jsonObj转换为实体类对象
            BaseDbTableProcess tableProcess = jsonObj.toJavaObject(BaseDbTableProcess.class);
            String sourceTable = tableProcess.getSourceTable();
            String sourceType = tableProcess.getSourceType();
            String key = sourceTable + ":" + sourceType;
            configMap.put(key, tableProcess);
        }
        //释放资源
        rs.close();
        ps.close();
        conn.close();

    }

    public BaseDbTableProcessFunction(MapStateDescriptor<String, BaseDbTableProcess> mapStateDescriptor){
        this.mapStateDescriptor = mapStateDescriptor;
    }
    @Override
    public void processElement(JSONObject jsonObj, BroadcastProcessFunction<JSONObject, String, JSONObject>.ReadOnlyContext readOnlyContext, Collector<JSONObject> collector) throws Exception {
        //获取业务数据库表表名
        String table = jsonObj.getString("table");
        //获取对表进行的操作的类型
        String type = jsonObj.getString("type");
        //拼接key
        String key = table + ":" + type;
        //获取广播状态
        ReadOnlyBroadcastState<String, BaseDbTableProcess> broadcastState = readOnlyContext.getBroadcastState(mapStateDescriptor);
        //根据key到广播状态中获取对应的配置信息
        BaseDbTableProcess tableProcess = null;

        if ((tableProcess = broadcastState.get(key))!=null
                || (tableProcess = configMap.get(key))!=null) {
            //将需要动态分流处理的事实表数据(只需要data部分) 发送到下游
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");
            //获取输出目的地
            String sinkTable = tableProcess.getSinkTable();
            //在向下游发送数据前，过滤掉不需要传递的属性
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj, sinkColumns);
            //在向下游发送数据前，补充输出目的地
            dataJsonObj.put("sink_table", sinkTable);
            //在向下游发送数据前，补充事件时间
            Long ts = jsonObj.getLong("ts");
            dataJsonObj.put("ts", ts);

            collector.collect(dataJsonObj);
        }
    }
    //过滤
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] columnArr = sinkColumns.split(",");
        List<String> columnList = Arrays.asList(columnArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry -> !columnList.contains(entry.getKey()));
    }

    @Override
    public void processBroadcastElement(String str, BroadcastProcessFunction<JSONObject, String, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
        //获取数据，转换成JSONObj格式、
        JSONObject jsonObj = JSON.parseObject(str);
        //获取数据类型
        String op = jsonObj.getString("op");
        //获取状态中的数据
        BroadcastState<String, BaseDbTableProcess> broadcastState = context.getBroadcastState(mapStateDescriptor);
        //判断数据类型
        if (op.equals("d")){
            //从广播状态中，将对应的配置删除掉
            BaseDbTableProcess before = jsonObj.getObject("before", BaseDbTableProcess.class);
            String sourceTable = before.getSourceTable();
            String sourceType = before.getSourceType();
            String key = sourceTable + ":" + sourceType;
            broadcastState.remove(key);
            configMap.remove(key);
        }else {
            //将配置信息放到(更新)广播状态中
            BaseDbTableProcess after = jsonObj.getObject("after", BaseDbTableProcess.class);
            String sourceTable = after.getSourceTable();
            String sourceType = after.getSourceType();
            String key = sourceTable + ":" + sourceType;
            broadcastState.put(key, after);
            configMap.put(key, after);
        }
    }
}
